<script setup>
import { useUserStore  } from '../stores/user'
import { CircleCloseFilled } from '@element-plus/icons-vue'
import getUser  from "../api/getuser.js"
import getUserById from '../api/getUserById.js';
import getUserEntity from "../api/getUserEntity";
import islogin from '../api/isLogin';
import getImage from '../api/getImage';
import { useRouter } from 'vue-router';
import imageShow from './imageShow.vue';
import getArticleList from "../api/getArticleList.js"
import {ref ,onBeforeMount,computed} from "vue"
import getArticlesByUserId from "../api/getArticleByUserId.js"
import { Setting , Plus } from '@element-plus/icons-vue'
import updateUser from "../api/updateUser.js"
import confirm from '../api/confirm.js'
import sender from '../api/sendConfirmCode.js'
import isAdmin  from '../api/isAdmin';
import updateArticle from '../api/updateArticle.js'
import updateArticleAdmin from '../api/updateArticleAdmin'

const timeOut = ref(0)
const id = ref(0)
const userId = ref(localStorage.getItem("userId"))
const urlParams = new URLSearchParams(window.location.search);
const imageValue = ref("")
const user = ref({})
const userInforms= ref({})
const use = useRouter()
const article = ref({})
const articlesList = ref({})
const userInform = useUserStore()
const visible = ref(false)
const dispose= ref({})
const disposeFlag = ref(false)
const disposeUser = ref({})
const oldUser = ref({})
const confirm_code = ref("")
const imageUrl = ref("")
const image_id = ref("")
const an_state = ref(false)
const url = "http://localhost:5173/api/image/upload?token=Bearer " + localStorage.getItem("jwttoken")
const getImageUrl = computed(() =>{dispose.value.imageId})
try{
        if(userInform.userId === ""){
        getUser({
        }).then(function (response) {
        if(response.status == 200 && response.data.userId!=undefined)
        {
            userInform.userId = response.data.userId ;
            userInform.username = response.data.userName ;
            userInform.image = response.data.imageId;
            userInform.article =  response.data.articleId ;
        }
        else {
            localStorage.removeItem("jwttoken");
            localStorage.removeItem("userId");
        }
        })
        }
    }
    catch(error)
    {
        loading.value = false ;
        console.error(error);
    }

onBeforeMount(()=>{
    id.value = urlParams.get('userId');
    if(id.value==null)
    {
    id.value = localStorage.getItem("userId")
    }

    isAdmin().then((res)=>{
        if(res.status = 200)
        an_state.value= true
    })

getUserById(id.value).then((res)=>{
        if(res.status == 200)
        {
            userInforms.value = res.data
            getImage(userInforms.value.imageId).then((res)=>
            {
                if(res.status == 200)
                imageValue.value = res.data 
            })
            getArticleList(userInforms.value.articleId).then((res)=>{
                if(res.status == 200)
                {
                    article.value = res.data
                    article.value = article.value.reverse()
                    console.log(article.value)
                }
            })
            console.log(res.data)
        }
    })
    getUserEntity(id.value).then((res)=>{
        if(res.status == 200)
        {
            user.value = res.data
            console.log(res.data)
        }
    })
    getArticlesByUserId(id.value).then((res)=>{
        if(res.status == 200)
        {
            articlesList.value = res.data
            console.log(res.data)
        }
    })
})


function timerHandler () {
            setInterval(()=>{timeOut.value--},1000)
        }

function funcArticle(id){
    use.push("/article?param="+id)
}
  //判断是否登录 并获得chatlist 

function AdminSet(item){
    visible.value = true
    dispose.value = item
}

function getUserByLink(userId){
    
    getUserEntity(userId).then((res)=>{
        if(res.status == 200)
        {
            disposeUser.value = res.data
            oldUser.value = res.data
            console.log(res.data)
            disposeFlag.value = true
        }
    })
}

function updateUserByDraw(user){
    updateUser(user,confirm_code.value).then((res)=>{
        if(res.status == 200)
        {
            console.log(res)
        }
    })
}

function updateArticleByDraw(){
    if(an_state.value && dispose.value.userId != localStorage.getItem("userId"))
    {
        updateArticleAdmin({
            id:dispose.value.id,
            state:dispose.value.state,
        }).then((res)=>{
            if(res.status == 200)
            {
                dispose.value = res.data
                ElMessage.success("修改成功")
            }
        })
    }
    else {
        updateArticle({
            id:dispose.value.id,
            author:dispose.value.author,
            content:dispose.value.content,
            state:dispose.value.state,
            imageId:dispose.value.imageId == null ? ""  : (dispose.value.imageId),
            images:dispose.value.images == null ?  "" : (dispose.value.images),
            title:dispose.value.title,
            type:dispose.value.type,
            userId:dispose.value.userId
        }).then((res)=>{
            if(res.status == 200)
            {
                dispose.value = res.data
                ElMessage.success("修改成功")
            }
        })
    }
}

function sendConfirmCode(){
        if(oldUser.value.email.trim === "" || oldUser.value.email == undefined || oldUser.value.email === "")
        {
            ElMessage({message:'请输入邮箱',
            type:"error"})
            return null
            }
            timeOut.value = 180
            timerHandler()
            sender(oldUser.value.email).then(
            (res)=>{
            if( res.status == "200" ){
            }
            }
            )
        }
    function successHandler (res,file){ 
        image_id.value =res
        imageUrl.value = URL.createObjectURL(file.raw);
        dispose.value.imageId = image_id.value
    }
    function beforeAvatarUpload(file) {
        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
            ElMessage.error('上传头像图片只能是 JPG / PNG 格式!');
        }
        if (!isLt2M) {
            ElMessage.error('上传头像图片大小不能超过 2MB!');
        }


        return isJPG && isLt2M;
        }

    function byBtn()
    {
        visible.value = true;
        getUserByLink(userId.value)
    }
</script>

<template>
    <el-button v-if="an_state || userId == userInforms.userId" style="position: absolute; left: 90%; top: 140px ;" @click="byBtn()" :icon="Setting" circle></el-button>
    <el-container>
    <el-header style="width: 100%;">
        <Header></Header>
    </el-header>
    <el-main class="main-box">
    <el-descriptions
    title=" User information "
    direction="vertical"
    :column="4"
    :size="40"
    border
    >
    <el-descriptions-item label="头像" :span="4" style="height: 120px;"><el-avatar class="image-box" shape="square" :size="100" :src="imageValue" /></el-descriptions-item>
    <el-descriptions-item label="用户名"><div class="text-box">{{ userInforms.userName }}</div></el-descriptions-item>
    <el-descriptions-item label="姓名"><div class="text-box">{{ user.fullName }}</div></el-descriptions-item>
    <el-descriptions-item label="邮箱"><div class="text-box">{{ user.email }}</div></el-descriptions-item>
    <el-descriptions-item label="喜爱">
        <el-tag size="small">{{ user.type }}</el-tag>
    </el-descriptions-item>
    <el-descriptions-item label="地址："
        >{{ user.address }}
    </el-descriptions-item>
    </el-descriptions>
    <br>
    <h3>所创建过的</h3>
    <div class="read-box" style="overflow: auto">
    <ul
    >
        <li class="display-item" v-for="item in articlesList" :key="item" >
            <el-card shadow="hover" class="card-box"> 
                <div style="width: 100px;"  @click="funcArticle(item.id)"><imageShow class="image-box" :value="item.imageId"></imageShow></div>
                <nav class="content-box">
                <div class="title"  @click="funcArticle(item.id)">                  
                    <el-popover
                    placement="right" :width="400"
                    trigger="hover"
                    >
                        <template #reference>
                            <a href="#">{{ item.title }}</a>
                        </template>
                        <div v-html="item.content.substring(0,60)">
                        </div>
                    </el-popover></div>
                <div class="author">发布者： <el-link >{{ item.userId }}</el-link> &nbsp;&nbsp;&nbsp; <br>作者：{{ item.author }}</div>
                <div class="type"><el-tag size="small">{{ item.type }}</el-tag> &nbsp; <el-tag size="small">{{ item.state==true?"可见":"不可见" }}</el-tag></div>
                </nav>
                <div class="btn-box" v-show="item.userId == userId"> <el-button :icon="Setting" @Click="AdminSet(item)" circle> </el-button> </div>
            </el-card>
        </li>
    </ul>
    <br>
    </div>
    <h3>最近访问过的文章</h3>
    <div class="read-box" style="overflow: auto">
    <ul
    >
        <li class="display-item" v-for="item in article" :key="item" >
            <el-card shadow="hover" class="card-box"> 
                <div style="width: 100px;"  @click="funcArticle(item.id)"><imageShow class="image-box" :value="item.imageId"></imageShow></div>
                <nav class="content-box">
                    <div class="title" >                  
                            <a href="#"  @click="funcArticle(item.id)">{{ item.title }}</a>
                    </div>
                <div class="author">发布者： <el-link>{{ item.userId }}</el-link> &nbsp;&nbsp;&nbsp; <br>作者：{{ item.author }}</div>
                <div class="type"><el-tag size="small">{{ item.type }}</el-tag></div>
                
                </nav>
            </el-card>
        </li>
    </ul>
    <br>
    </div>
    </el-main>
    </el-container>
    <el-drawer v-model="visible" :show-close="false">
    <template #header="{ close, titleId, titleClass }">
        <h4 :id="titleId" :class="titleClass">{{ dispose.title }}</h4>
        <el-button type="danger" @click="close">
        <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
        Close
        </el-button>
    </template>
    <div>发布者：<el-link @click="getUserByLink(dispose.userId)">{{ dispose.userId }}</el-link>&nbsp;&nbsp;&nbsp;编号：<el-link @click="use.push('/article?param='+dispose.id)">{{ dispose.id }}</el-link></div>
    <br>
    <div>类型：<el-input v-model="dispose.type"/></div>
    <br>
    <div>作者：<el-input v-model="dispose.author"/></div>
    <br>
    <div>发布日期：{{dispose.authorCreatedTime}} </div>
    <br>
    <div>
        封面：<br>
            <imageShow style="width: 160px; height: 160px;" :value="dispose.imageId"></imageShow>
        <el-upload
        class="avatar-uploader"
        :action="url"
        :show-file-list="true"
        :on-success = "successHandler"
        :before-upload="beforeAvatarUpload">
        
        <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
        <el-icon v-else class="el-icon-plus avatar-uploader-icon"> <Plus></Plus> </el-icon>
        </el-upload>
    </div>
    <br>
    内容：<br>
    <div v-html=" dispose.content " class="dispose-box"></div>
    <br>
    <div v-if="dispose.state || an_state" >状态：<el-switch v-model="dispose.state"/></div>
    <div v-else>状态：<el-switch v-model="dispose.state" disabled/></div>
    <br>
    <div>
        <el-button @click="updateArticleByDraw()" text>
            提交  
        </el-button>
    </div>
    
    
    <el-drawer
        v-model="disposeFlag"
        :append-to-body="true"
        :before-close="handleClose"
        >
            <div> 用户名： {{disposeUser.username}} &nbsp;&nbsp;&nbsp;权限: {{ disposeUser.role.slice(5) }} </div>
            <br>
            <div> 生日： <el-date-picker v-model="disposeUser.birthDate" type="date" /></div>
            <br>
            <div>邮箱 : <el-input v-model="disposeUser.email"/><el-button v-show="timeOut<=0" text @click="sendConfirmCode">发送</el-button></div>
            <div>验证码：<el-input v-model="confirm_code" style="width: 80px;"/> <span v-show="timeOut>0" style="margin-left:4%; color : #999" >有效时间:{{ timeOut }}</span></div>
            <br>
            <div> 全名：<el-input v-model="disposeUser.fullName"/> </div>
            <br>
            <div>地址：<el-input v-model="disposeUser.address"/></div>
            <br>
            <div><el-button text @click="updateUserByDraw(disposeUser)">   提交  </el-button></div>
    </el-drawer>

    </el-drawer>

</template>

<style>
    @import "../css/userInform.css"

</style>